import {WindowName} from "../../framework/reflect/WindowName";
import {WindowContent} from "../../framework/dialog/WindowContent";
import {DateUtil} from "../../framework/utils/DateUtil";
import {userProfit} from "../entity/UserProfit";
import Toast from "./Toast";
import {wxApi} from "../api/WxApi";
import {HttpResponse} from "../entity/HttpResponse";
import Wx from "../../framework/wx/Wx";
import {logger} from "../third-scripts/game_sdk/Logger";

const {ccclass, property} = cc._decorator;

@ccclass
@WindowName("AddMiniProgramDialog")
export default class AddMiniProgramDialog extends WindowContent {

    @property(cc.Node)
    private closeBtn: cc.Node = null;

    @property(cc.Node)
    private addFinger: cc.Node = null;


    @property(cc.Node)
    private getDiamondBtn: cc.Node = null;

    public onShow() {
        this.setClickListener(this.closeBtn, this.dismiss);
        this.setClickListener(this.getDiamondBtn, this.onGetDiamondClick);
        console.log("finger Pos:", this.addFinger.position, cc.winSize);
        if (cc.winSize.height / cc.winSize.width >= 1.8) {
            this.addFinger.y += 100;
            console.log("调整手指位置:", this.addFinger.position);
        }
        logger.sendEvent("打开")
    }

    private onGetDiamondClick() {
        if (DateUtil.isToday(userProfit.lastGetDiamondTs)) {
            Toast.showToast("今日已领取过啦~");
            return;
        }
        Wx.checkEnterFromMiniProgram().then(ret => {
            if (!ret) {
                Toast.showToast("需要从我的小程序进入才能领奖哦~");
                return;
            }
            this.getDiamond();
        });
    }

    private getDiamond() {
        Toast.showToast("领取中...");
        wxApi.time().then(resp => {
            if (!HttpResponse.isOk(resp)) {
                Toast.showToast("服务器异常,请稍后领取哦~");
                return
            }

            if (!DateUtil.isSameDay(cc.sys.now(), resp.data.time || 0)) {
                Toast.showToast("检测到本地时间异常,请稍后领取哦~");
                return
            }

            this.dismiss();

            userProfit.lastGetDiamondTs = +resp.data.time;
            userProfit.save();

            logger.sendEvent("我的小程序领奖");
        })
    }
};
